package com.lsk.mytuan.util;

public class Storager {
    private Storageable[] elements;

    public Storager () {
        this.elements = new Storageable[50];
    }

    private void expandElements () {
        Storageable[] newElements = new Storageable[this.elements.length + 50];
        for (int i = 0; i < this.elements.length; i++) {
            newElements[i] = this.elements[i];
        }
        this.elements = newElements;
    }

    public void put(Storageable element) {
        int index = element.getId() - 1;
        if (index >= this.elements.length) {
            expandElements();
        }
        this.elements[index] = element;
    }

    public Storageable get(int id) {
        int index = id - 1;
        if (index < 0 || index >= this.elements.length) {
            return null;
        }
        return this.elements[index];
    }

    public boolean delete (int id) {
        int index = id - 1;
        if (index < 0 || index >= this.elements.length) {
            return false;
        }
        this.elements[index] = null;
        return true;
    }

    public int length () {
        return this.elements.length;
    }

    @Override
    public String toString() {
        String result = "";
        for (int i = 0; i < this.elements.length; i++) {
            Storageable storageable = this.elements[i];
            if (storageable != null) {
                result += storageable.toString();
                result += "\r\n";
            }
        }
        return result;
    }
}
